//
//  QLShenyueHomeVC.m
//  神约
//
//  Created by qlwl on 17/1/19.
//  Copyright © 2017年 qlwl. All rights reserved.
//

#import "QLShenyueHomeVC.h"
#import "PageView.h"
#import "UIView+FrameKIt.h"
#import "PageItemModel.h"
#import "CDFlowLayout-swift.h"
#import "PageItemView.h"
#import "ImaOnRightBtn.h"
#import "NSString+Length.h"
#import "UIImage+MyIma.h"
#import "QLAllInvitedMeetVC.h"
#import "QLSkillInvitedMeetListVC.h"
#import "AMKLocationModel.h"
#import "QLPersonalTailorVC.h"


NSInteger NIMMaxItemCountInPage = 8;
NSInteger NIMPageRowCount     = 2;
NSInteger NIMPageColumnCount  = 4;
NSInteger NIMButtonBegintLeftX = 0;
NSInteger NIMButtonItemWidth = 80;
NSInteger NIMButtonItemHeight = 60;

#define InteritemSpacing (10)
#define EdgeLeftOrRight ((iphoneWidth-2*InteritemSpacing)/10 + InteritemSpacing)
#define CellWidth ((iphoneWidth-2*InteritemSpacing)*4/5)
#define CellHeight (CellWidth * 3/2)


@interface QLShenyueHomeVC ()<PageViewDataSource,PageViewDelegate,UICollectionViewDelegate , UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,AMapSearchDelegate,AMapLocationManagerDelegate>
@property (strong, nonatomic) PageView *itempageView;
@property (weak, nonatomic) IBOutlet UIView *pageBgView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, assign) BOOL isRefresh ; //

@property (nonatomic, strong) AMapLocationManager * locationManagerr ; // 
@property (nonatomic, strong) AMapSearchAPI * search  ; //

@end

@implementation QLShenyueHomeVC
{
    NSMutableArray                 *_mediaItems;
    NSMutableArray                 *_topItems;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setNavBarColor:NavBarTintColor];
    [self getMyNavBarWithNavTitle:@"首页" andRightTitle:nil andRightIma:@"homeSearchRightBar" and:^(int tag) {
        
    }];
    [self getMyNavBar];
    
    _itempageView = [[PageView alloc] initWithFrame:CGRectZero];
    _itempageView.pageViewDelegate = self;
    _itempageView.dataSource = self;
    _itempageView.frame = self.pageBgView.bounds;
    _itempageView.autoresizingMask = UIViewAutoresizingFlexibleWidth| UIViewAutoresizingFlexibleHeight;
    [self.pageBgView addSubview:_itempageView];
    
    [self getTopItems];
    [self genMediaButtons];
    [_itempageView reloadData];
    
    
    
    CDFlowLayout * layout = [[CDFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = InteritemSpacing;
    layout.sectionInset = UIEdgeInsetsMake(0, EdgeLeftOrRight, 0, EdgeLeftOrRight);
    float collectionHeight = iphoneHeight - 64 - 49 - 160 - 2 * 8;
    layout.itemSize = CGSizeMake(CellWidth, CellHeight < collectionHeight?CellHeight:collectionHeight);
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.showsHorizontalScrollIndicator = NO;

    [self.collectionView reloadData];
    
    
    self.locationManagerr = [[AMapLocationManager alloc] init];
    [self.locationManagerr setDesiredAccuracy:kCLLocationAccuracyBest];
     //带逆地理（返回坐标和地址信息）
    self.locationManagerr.delegate = self;
    self.locationManagerr.reGeocodeTimeout = 10;
    [self.locationManagerr setLocatingWithReGeocode:NO];
    [self.locationManagerr startUpdatingLocation];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
//    [self.locationManagerr requestLocationWithReGeocode:NO completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//        if (error)
//        {
//            NSLog(@"locationAdress--error--%@",error);
//            return;
//        }
//        
////        [self upUserLocationNet:location.coordinate andCityName:regeocode.city andAddress:regeocode.formattedAddress];
//        
//        NSLog(@"开始反地理编码");
//        AMapSearchAPI * search = [[AMapSearchAPI alloc] init];
//        search.delegate = self;
//        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
//        regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
//        regeo.requireExtension =YES;
//        regeo.radius = 1000;
//        [search AMapReGoecodeSearch:regeo];
//    }];
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    [manager stopUpdatingLocation];
    
    NSLog(@"开始反地理编码");
    
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    regeo.requireExtension =YES;
    regeo.radius = 200;
    [self.search AMapReGoecodeSearch:regeo];
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil)
    {
        //通过AMapReGeocodeSearchResponse对象处理搜索结果
        NSString *result = [NSString stringWithFormat:@"ReGeocode: %@", response.regeocode];
        NSLog(@"%@ -- %@ --%@",response.regeocode.formattedAddress,response.regeocode.addressComponent.streetNumber.street,response.regeocode.addressComponent.streetNumber.number );
        NSLog(@"ReGeo: %@", result);
        CLLocationCoordinate2D  coor2d = {request.location.latitude,request.location.longitude};
        [self upUserLocationNet:coor2d andCityName:response.regeocode.addressComponent.city andAddress:response.regeocode.formattedAddress];
    }
}

- (void)searchBar:(UIButton *)btn
{
    btn.selected = !btn.selected;
}
- (void) getMyNavBar
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, iphoneWidth - 120, 44)];
    UILabel * titLab = [[UILabel alloc] init];
    titLab.text = @"神约";
    titLab.font = [UIFont systemFontOfSize:18];
    titLab.textColor = [UIColor whiteColor];
    [titLab sizeToFit];
    titLab.center = CGPointMake(view.f_width/2, view.f_height/2);
    [view addSubview:titLab];
    
    ImaOnRightBtn * btn = [ImaOnRightBtn buttonWithType:UIButtonTypeCustom];
    btn.titByteLenght = 8;
    [btn addTarget:self action:@selector(searchBar:) forControlEvents:UIControlEventTouchUpInside];
    //btn.backgroundColor = [UIColor redColor];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.4] forState:UIControlStateHighlighted];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    btn.frame = CGRectZero;
    [btn setTitle:@"北京" forState:UIControlStateNormal];
    //UIImage * ima = [[UIImage imageNamed:@"annotationDownArrow"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage * ima = [UIImage imageNamed:@"annotationDownArrow"];
    [btn setImage:ima forState:UIControlStateNormal];
    [btn setImage:[UIImage image:ima rotation:UIImageOrientationDown] forState:UIControlStateSelected];
    [btn sizeToFit];
    btn.f_left = titLab.f_right + 4;
    btn.f_centerY = view.f_height/2 + 2;
    [view addSubview:btn];
    self.navigationItem.titleView = view;
}


#pragma mark getTopResouce
- (void) getTopItems
{
    _topItems = [NSMutableArray array];
    NSArray * titArray = @[@"",@"",@"",@"",@"技能互助",@"私人订制",@"私人订制",@"私人订制"];
    NSArray * imaArray = @[@"homeTop吃",@"homeTop喝",@"homeTop玩",@"homeTop乐",@"homeTop技能",@"homeTop订制1",@"homeTop订制2",@"homeTop订制3"];
    for (int i = 0; i < titArray.count; i++) {
        PageItemModel * model = [[PageItemModel alloc] init];
        model.title = titArray[i];
        model.normalImage =  imaArray[i];
        model.tag = i;
        [_topItems addObject:model];
    }
}

- (void)genMediaButtons
{
    NSMutableArray *mediaItems = [[NSMutableArray alloc] init];
    [_topItems enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PageItemModel *item = (PageItemModel *)obj;
        PageItemView * itemView = [[PageItemView alloc] initWithFrame:CGRectZero];
        [itemView.btn setImage:[UIImage imageNamed:item.normalImage] forState:UIControlStateNormal];
        [itemView.btn setImage:[UIImage imageNamed:item.selectedImage] forState:UIControlStateHighlighted];
        itemView.btn.tag = item.tag;
        itemView.tag = item.tag;
        itemView.titLab.text = item.title;
        [mediaItems addObject:itemView];
    }];
    _mediaItems = mediaItems;
}


#pragma mark PageViewDataSource
- (NSInteger)numberOfPages:(PageView *)pageView
{
    NSInteger count = [_mediaItems count] / NIMMaxItemCountInPage;
    count = ([_mediaItems count] % NIMMaxItemCountInPage == 0) ? count: count + 1;
    return MAX(count, 1);
}

- (UIView*)mediaPageView:(PageView*)pageView beginItem:(NSInteger)begin endItem:(NSInteger)end
{
    UIView *subView = [[UIView alloc] init];
    NSInteger span = (iphoneWidth - NIMPageColumnCount * NIMButtonItemWidth) / (NIMPageColumnCount);
    CGFloat startY          = NIMButtonBegintLeftX;
    NSInteger coloumnIndex = 0;
    NSInteger rowIndex = 0;
    NSInteger indexInPage = 0;
    for (NSInteger index = begin; index < end; index ++)
    {
        PageItemView * itemView = (PageItemView *)[_mediaItems objectAtIndex:index];
        [itemView.btn addTarget:self action:@selector(onTouchButton:) forControlEvents:UIControlEventTouchUpInside];
        //计算位置
        rowIndex    = indexInPage / NIMPageColumnCount;
        coloumnIndex= indexInPage % NIMPageColumnCount;
        CGFloat x = span/2 + (NIMButtonItemWidth + span) * coloumnIndex;
        CGFloat y = 0.0;
        if (rowIndex > 0)
        {
            y = rowIndex * NIMButtonItemHeight + startY + 10 + 6 + 8;
        }
        else
        {
            y = rowIndex * NIMButtonItemHeight + startY + 10 + 6;
        }
        [itemView setFrame:CGRectMake(x, y, NIMButtonItemWidth, NIMButtonItemHeight)];
        NSLog(@"%@",itemView);
        [subView addSubview:itemView];
        indexInPage ++;
    }
    return subView;
}

- (UIView*)oneLineMediaInPageView:(PageView *)pageView
                       viewInPage: (NSInteger)index
                            count:(NSInteger)count
{
    UIView *subView = [[UIView alloc] init];
    NSInteger span = (iphoneWidth - count * NIMButtonItemWidth) / (count +1);
    
    for (NSInteger btnIndex = 0; btnIndex < count; btnIndex ++)
    {
        PageItemView * itemView = (PageItemView *)[_mediaItems objectAtIndex:index];
        [itemView.btn addTarget:self action:@selector(onTouchButton:) forControlEvents:UIControlEventTouchUpInside];
        CGRect iconRect = CGRectMake(span + (NIMButtonItemWidth + span) * btnIndex, 58, NIMButtonItemWidth, NIMButtonItemHeight);
        [itemView setFrame:iconRect];
        [subView addSubview:itemView];
    }
    return subView;
}

- (UIView *)pageView: (PageView *)pageView viewInPage: (NSInteger)index
{
    if ([_mediaItems count] == 2 || [_mediaItems count] == 3) //一行显示2个或者3个
    {
        return [self oneLineMediaInPageView:pageView viewInPage:index count:[_mediaItems count]];
    }
    
    if (index < 0)
    {
        assert(0);
        index = 0;
    }
    NSInteger begin = index * NIMMaxItemCountInPage;
    NSInteger end = (index + 1) * NIMMaxItemCountInPage;
    if (end > [_mediaItems count])
    {
        end = [_mediaItems count];
    }
    return [self mediaPageView:pageView beginItem:begin endItem:end];
}
#pragma mark - button actions
- (void)onTouchButton:(id)sender
{
    NSInteger tag = [(UIButton *)sender tag];
    NSLog(@"%ld",tag);
    
    if (tag <4) {
        QLAllInvitedMeetVC * meetListVC = [NSString instantiateViewControllerWithIdentifier:@"QLAllInvitedMeetVC" andSBName:@"Home"];
        [self.navigationController pushViewController:meetListVC animated:YES];
    }else if (tag == 4) {
        QLSkillInvitedMeetListVC * skillListVC = [NSString instantiateViewControllerWithIdentifier:@"QLSkillInvitedMeetListVC" andSBName:@"Home"];
        [self.navigationController pushViewController:skillListVC animated:YES];
    }else {
        QLPersonalTailorVC * tailorVC = [NSString instantiateViewControllerWithIdentifier:@"QLPersonalTailorVC" andSBName:@"Home"];
        
        [self.navigationController pushViewController:tailorVC animated:YES];
    }
}

#pragma mark CollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"QLShenyueHomeCell" forIndexPath:indexPath];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView * reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];

    
    return reusableView;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView != self.collectionView) {
        return;
    }
    if (scrollView.contentOffset.x + scrollView.f_width > (scrollView.contentSize.width+ 30 + 30)) {
        self.isRefresh = YES;
    }else{
        self.isRefresh = NO;
    }
}
- (void)setIsRefresh:(BOOL)isRefresh
{
    if (_isRefresh != isRefresh) {
        _isRefresh = isRefresh;
        if (_isRefresh) {
            
        }
    }
}

//定位
- (void) upUserLocationNet:(CLLocationCoordinate2D)coor2D andCityName:(NSString *)cityName andAddress:(NSString *)address
{
    QLLoginModel *loginModel = [QLLoginModel accountFromSandbox];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"latitude"] = [NSString stringWithFormat:@"%f",coor2D.latitude];
    postDict[@"longitude"] = [NSString stringWithFormat:@"%f",coor2D.longitude];
    postDict[@"userid"] = loginModel.userId;
    postDict[@"cityname"] = cityName;
    postDict[@"address"] = address;
    [QLNetWorking postJSONWithUrl:QLUpUserLocationURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        NSLog(@"%@",result);
    } fail:^(NSError *error) {
        
    }];
}


@end



